package com.hontech.bvapp2.service

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.cbor.Cbor
import kotlinx.serialization.decodeFromByteArray
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import java.io.IOException
import java.util.concurrent.TimeUnit

private const val BASE_URL = "http://local.hontech-rdcenter.com:18880"

private val client = OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS)
    .readTimeout(60, TimeUnit.SECONDS)
    .build()


@Serializable
class ServiceException (
    @SerialName("err_code")
    val ec: Int,

    @SerialName("err_msg")
    val msg: String
) : IllegalStateException("$ec => $msg")


@OptIn(ExperimentalSerializationApi::class)
fun parseResp(resp: Response) {
    if (!resp.isSuccessful) {
        throw IOException("网络错误:${resp.message}")
    }
    val respHead = resp.header("resp") ?: throw IOException("not resp")
    if (respHead != "ok") {
        val body = resp.body?.bytes() ?: throw IOException("not body")
        val err = Cbor.decodeFromByteArray<ServiceException>(body)
        throw err
    }
}

@OptIn(ExperimentalSerializationApi::class)
inline fun<reified T> Response.parse(): T {
    return Cbor.decodeFromByteArray<T>(this.body?.bytes() ?: throw IOException("not resp"))
}

object Http {

    fun post(url: String, body: ByteArray, headers: Array<Pair<String, String>> = emptyArray()): Response {
        val builder = Request.Builder()
        for (header in headers) {
            builder.addHeader(header.first, header.second)
        }
        val req = builder
            .post(body.toRequestBody())
            .url("${BASE_URL}$url")
            .build()
        val resp = client.newCall(req).execute()
        parseResp(resp)
        return resp
    }

    fun get(url: String, headers: Array<Pair<String, String>> = emptyArray()): Response {
        val builder = Request.Builder()
        for (header in headers) {
            builder.addHeader(header.first, header.second)
        }
        val req = builder
            .get()
            .url("${BASE_URL}$url")
            .build()
        val resp = client.newCall(req).execute()
        parseResp(resp)
        return resp
    }

}


















